package jmcnet.libcommun.security;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.log4j.Logger;

public class UserDetailsImpl implements UserDetails {
	private Logger log = Logger.getLogger(UserDetailsImpl.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private SecurityVO userDetailsVO=null;
	private GrantedAuthority[] authorities=null;

	public UserDetailsImpl(SecurityVO userDetailsVO) {
		this.userDetailsVO = userDetailsVO;
		this.authorities = null; // lazily initialized
	}

	public SecurityVO getUserDetailsVO() {
		return userDetailsVO;
	}

	public String getUsername() {
		return userDetailsVO.getLogin();
	}
	
	public String getPassword() {
		return userDetailsVO.getPassword();
	}

	public boolean isAccountNonExpired() {
		return userDetailsVO.isAccountNonExpired();
	}

	public boolean isAccountNonLocked() {
		return userDetailsVO.isAccountNonLocked();
	}

	public boolean isCredentialsNonExpired() {
		return userDetailsVO.isCredentialsNonExpired();
	}

	public boolean isEnabled() {
		return userDetailsVO.isEnabled();
	}

	public GrantedAuthority[] getAuthorities() {
		log.info("Appel getAuthorities");

		// Authorities are initialized lazily
		if (authorities == null)
		{
			String[] roles = userDetailsVO.getRoles();
			if (roles != null) {
				authorities = new GrantedAuthorityImpl[roles.length];
				for (int i=0; i<roles.length; i++)
				{
					if (log.isDebugEnabled()) log.debug("Ajout du role :"+roles[i]);
					authorities[i] = new GrantedAuthorityImpl(roles[i]);
				}
			}
			else {
				log.warn("Attention : "+userDetailsVO.getLogin()+" n'a pas de role");
			}
		}
		
		GrantedAuthority[] ret = authorities.clone();
		log.info("fin getAuthorities : ["+ret.toString()+"]");
		return ret;
	}
}